<template>
    <div class="page">
        <gzg-search :config="searchConfig"
                    :showMore="true" 
                    :form="searchForm"
                    :label-width="120"
                    @search="search"></gzg-search>


            <div class="grid-wrap">
                <el-table style="width:100%;"
                        row-key="id"
                        :data="tableData">
                    <el-table-column label="角色类型" prop="account" width="160px" fixed></el-table-column>
                    <el-table-column label="手机号码" prop="mobile"></el-table-column>
                    <el-table-column label="姓名" prop="department_name"></el-table-column>
                    <el-table-column label="状态" prop="role_string"></el-table-column>
                    <el-table-column label="赠送商家账号额度" prop="role_string"></el-table-column>
                    <el-table-column label="赠送商家账号额度" prop="role_string"></el-table-column>

                    <el-table-column label="创建时间" prop="create_at"></el-table-column>
                    <el-table-column label="操作" fixed="right" width="120px">
                        <template #default="scope">
                            <el-button link type="primary" size="small" @click="edit(scope.row)" v-permission="'setting_rights_account_modify'">编辑</el-button>
                            <el-dropdown style="margin-top:2px" trigger="click" @command="handleCommand($event, scope)"> 
                                <gzg-icon name="more" color="#2770ee"></gzg-icon>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <div v-permission="'setting_rights_account_enable'">
                                            <el-dropdown-item command="enabled" >{{scope.row.enabled == 1 ? '禁用' : '启用'}}</el-dropdown-item>
                                        </div>
                                        <div v-permission="'setting_rights_account_reset_password'">
                                            <el-dropdown-item command="reset">重置密码</el-dropdown-item>
                                        </div>
                                        <div v-permission="'setting_rights_account_delete'">
                                            <el-dropdown-item command="delete" style="color:#f56c6c" >删除</el-dropdown-item>

                                        </div>

                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </template>
                    </el-table-column>

                </el-table>
            </div>
            <div class="page-wrap">
                <el-pagination
                    v-model:current-page="params.current"
                    v-model:page-size="params.size"
                    :page-sizes="[100, 200, 300, 400]"
                    layout="total, prev, pager, next"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />

            </div>
        <view-dialog :dialogVisible="dialogVisible" 
                    :id="detail_id"
                    :state="dialogState" 
                    @success="dialogSuccess"
                    @close="dialogVisible = false"></view-dialog>
        <el-dialog v-model="dialogResetVisible" width="480px" title="重置密码">
            <el-form ref="resetFormRef"
                 :model="resetForm"
                 :rules="resetFormRules"
                 :label-width="120">
                    <el-form-item prop="password" label="新密码:">
                        <el-input v-model="resetForm.password" :type="passwordShow ? 'text'  : 'password'" placeholder="请设置登录密码">
                            <template #suffix>
                                <el-icon @click.stop="passwordShow = !passwordShow" style="cursor: pointer;">
                                    <Hide v-if="!passwordShow" /> 
                                    <View v-else />
                                </el-icon>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="password_confirm" label="确认密码">
                        <el-input v-model="resetForm.password_confirm" :type="rePasswordShow ? 'text' : 'password'" placeholder="请确认登录密码">
                            <template #suffix>
                                <el-icon @click.stop="rePasswordShow = !rePasswordShow" style="cursor: pointer;">
                                    <Hide v-if="!rePasswordShow" /> 
                                    <View v-else />
                                </el-icon>
                            </template>
                        </el-input>
                    </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancelReset">取 消</el-button>
                    <el-button type="primary" @click="submitReset(resetFormRef)">确 定</el-button>
                </div>
            </template>
            
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, computed ,onMounted } from 'vue'
import { InfoFilled, Plus, Search, Hide, View  } from '@element-plus/icons-vue'
import { ElMessageBox,ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

import { assign } from 'lodash'

import viewDialog from './component/view-dialog/index'

import systemStore from '@/store/modules/system'

import { getAccountList,toggleAccount,deleteAccount,resetAccountPassword } from 'services/setting'

import type {User} from './index'

const $systemStore = systemStore()


const searchForm = reactive({
    type:'',
    name:'',
    mobile: '',
    status:'',
})

const searchConfig = reactive([{
    id:'type',
    label:'角色类型',
    placeholder:'请选择角色类型',
    type: 'select',
    enum:'agent_type_list'
},{
    id:'name',
    label:'姓名',
    placeholder:'请输入姓名',
    type: 'input'
},{
    id:'mobile',
    label:'手机号',
    placeholder:'请输入手机号',
    type: 'input'
},{
    id:'status',
    label:'状态',
    placeholder:'请选择状态',
    type: 'select',
    enum:'seller_status_list'
}])



const dialogState = ref('edit')

const dialogVisible = ref(false)  

const dialogResetVisible = ref(false)

const resetFormRef = ref<FormInstance>()

const passwordShow = ref(false)
const rePasswordShow = ref(false)

const resetForm = reactive({
    id:0,
    password:'',
    password_confirm:''
})

const checkPassword = (rule:any,value:any,callback:any) => {
    var reg = /(?!^[0-9]+$)(?!^[a-z]+$)(?!^[A-Z]+$)(?!^[^A-z0-9]+$)^[^\s\u4e00-\u9fa5]/

    if (value === '') {
        callback(new Error('请输入登录密码'))
    } else if (value.length < 6) {
        callback(new Error('密码最少6位'))
    } else if (value.length > 16) {
        callback(new Error('密码最多16位'))

    } else if (!reg.test(value)) {
        callback(new Error('密码需同时包含数字/字母/特殊符号，两种及以上组合'))

    } else {
        callback()
    }
}

const checkRePassword = (rule:any,value:any,callback:any) => {
    if (value != resetForm.password){
        callback(new Error('与登录密码不一致'))

    } else {
        callback()
    }
}

const resetFormRules = reactive<FormRules>({
   password:[{validator:checkPassword,required:true, trigger:'blur'}],
   password_confirm:[{required:true, validator:checkRePassword, trigger:'blur'}]
})

const params = ref({
    type:'',
    name:'',
    mobile: '',
    status:'',
    current:1,
    size:20
})

const search = (searchParams:any) => {

    assign(params.value, searchParams)

    params.value.current = 1

    getList()
}

const detail_id = ref()

const add = () => {
    dialogState.value = 'add'
    detail_id.value = undefined
    dialogVisible.value = true;
}

const edit = (row:User) => {
    dialogState.value = 'edit'
    dialogVisible.value = true
    detail_id.value = row.id
}


const tableData = ref<User[]>([])
const total = ref(0)

const getList = () => {
    getAccountList(params.value).then((res:any) => {
        tableData.value = res.list || [];
        total.value = res.total || 0
    })
}

const handleSizeChange = (val: number) => {
    params.value.size = val
    params.value.current = 1
    getList();
}

const handleCurrentChange = (val:number) => {
    params.value.current = val
    getList()
} 

const handleCommand = (command:string, scope:any) => {
    console.log(command, scope)
    switch (command) {
        case 'enabled':
            handleEnable(scope.row)
            break;
        case 'delete':
            handleDelete(scope.row)
            break;
        case 'reset':
            handleReset(scope.row)
            break;
        default:
            break;
    }
}

const handleReset = (row:User) => {
    resetForm.id = row.id || 0
    dialogResetVisible.value = true
}

const cancelReset = () => {
    dialogVisible.value = false
}

const submitReset = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            resetAccountPassword(resetForm).then((res:any) => {
                dialogVisible.value = false

                ElMessage.success('操作成功')
            })
        } else {
            console.log('error submit', fields)
        }
    })
}

const handleDelete = (row:User) => {
    ElMessageBox.confirm(`账号删除后不可恢复，确定删除“${row.account}”?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then((result) => {
        deleteAccount({id:row.id || undefined}).then(res => {
            getList()
            ElMessage.success('删除成功')
        })
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}

const handleEnable = (row:User) => {
    let enabled = row.enabled;
    ElMessageBox.confirm(`确认进行【${enabled === 1 ? '禁用' : '启用'}】操作`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        toggleAccount({
            id:row.id || undefined,
            enabled: enabled === 1 ? false : true
        }).then(res => {
            getList()
            ElMessage.success('操作成功')
        })
    }).catch(() => {
        ElMessage.info('已取消操作')
    })
}

const dialogSuccess = () => {
    getList();
    dialogVisible.value = false
}

const dict = computed<any>(() => {
    return $systemStore.dict
})

onMounted(() => {
    // getList()
})
</script>
<style lang="scss">
.tips{
    height: 40px;
    width: 100%;
    display: flex;
    align-items: center;
    font-size: 14px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    line-height: 22px;
    margin-bottom: 24px;

    .text{
        
        color: #606266;
        margin-left: 9px;
    }

    .link{
        color: #2770EE;
        margin-left: 8px;
        text-decoration: none;
    }
}
</style>
